const BooksTypes = require('../model/BooksTypes');
const Books = require('../model/Books');
const sequelize = require('../config/database');
const Sequelize = require('sequelize');
const { Op } = require('sequelize');
const fs = require('fs');
const { promisify } = require('util');
const unlinkPromisify = promisify(fs.unlink);

let booksTypeController = {};
booksTypeController.getType = async (req, res) => {
  let { page, pageSize } = req.query;
  page = parseInt(page) || 1;
  pageSize = parseInt(pageSize) || 6;
  let { count, rows } = await BooksTypes.findAndCountAll({
    offset: (page - 1) * pageSize,
    limit: pageSize,
  });
  // 查询总类型
  let typeCount;
  sequelize
    .query('SELECT count(*) as total FROM BooksTypes', {
      type: Sequelize.QueryTypes.SELECT,
    })
    .then((count) => {
      typeCount = count[0].total;
      res.json({ rows, typeCount });
    })
    .catch((err) => {
      console.error('查询失败:', err);
    });
};
booksTypeController.searchType = async (req, res) => {
  let { content } = req.query;
  let data = await BooksTypes.findAll({
    where: { name: { [Op.like]: `%${content}%` } },
  });
  res.json(data);
};
booksTypeController.addType = async (req, res) => {
  let { name } = req.body;
  let data = await BooksTypes.findOne({ where: { name } });
  // console.log(data);
  if (data) {
    res.json({ code: 20003, message: '已含有这个分类，请重新输入' });
    return;
  }
  BooksTypes.create({
    name,
  })
    .then(() => {
      res.json({ code: 20000, message: '添加成功' });
    })
    .catch(() => {
      res.json({ code: 20001, message: '添加失败' });
    });
};

booksTypeController.editType = async (req, res) => {
  let { id, name } = req.params;
  let data = await BooksTypes.update({ name }, { where: { id } });
  if (data) {
    res.json({ code: 20000, message: '编辑成功' });
    return;
  }
  res.json({ code: 20001, message: '编辑失败' });
};

booksTypeController.getTypeBooks = async (req, res) => {
  let { cateId } = req.query;
  let data = await Books.findAll({ where: { cate_id: cateId } });
  if (data.length) {
    res.json({ code: 20000 });
  } else {
    res.json({ code: 20001 });
  }
};

booksTypeController.delType = async (req, res) => {
  let { cateId } = req.params;
  await BooksTypes.destroy({ where: { id: cateId } });
  let data = await Books.findAll({ where: { cate_id: cateId } });
  data.forEach(async (item) => {
    item.dataValues.picture && (await unlinkPromisify(item.dataValues.picture));
  });
  await Books.destroy({ where: { cate_id: cateId } })
    .then(() => {
      res.json({ code: 20000, message: '删除成功' });
    })
    .catch(() => {
      res.json({ code: 20001, message: '删除失败' });
    });
};
module.exports = booksTypeController;
